﻿using Main.Extend.Attributes;
using Microsoft.Extensions.Configuration;
using System.Text;

namespace Main.Common
{
    /// <summary>
    /// 请求帮助类
    /// </summary>
    [Provider, Inject]
    public class Http : BaseCommon
    {
        public Http(IConfiguration configuration) : base(configuration)
        {
        }

        public async Task<string> HttpGetAsync(string Url)
        {
            try
            {
                using (HttpClient _Client = new HttpClient())
                {

                    var Response = await _Client.GetAsync(Url);
                    Response.EnsureSuccessStatusCode();
                    var result = await Response.Content.ReadAsStringAsync();
                    Response.Dispose();
                    return result;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public async Task<string> HttpPostAsync(string Url, string? postData = null, string? contentType = null, Dictionary<string, string>? headers = null)
        {
            try
            {
                using (HttpClient _Client = new HttpClient())
                {
                    if (headers != null)
                    {
                        foreach (var header in headers)
                            _Client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
                    if (contentType != null)
                    {
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                    }
                    var Response = await _Client.PostAsync(Url, httpContent);
                    Response.EnsureSuccessStatusCode();
                    var result = await Response.Content.ReadAsStringAsync();
                    Response.Dispose();
                    return result;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
